package com.monise.dao.BaseDao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import com.monise.dao.util.FactoryUtilOld;

public abstract class BaseDaoImpl<T, ID extends Serializable> implements
		BaseDao<T, ID> {

	@Override
	public void save(T entity){

		FactoryUtilOld factory = new FactoryUtilOld();
		EntityManager manager = factory.getFactory().createEntityManager();

		manager.getTransaction().begin();
		manager.persist(entity);
		manager.getTransaction().commit();
		manager.close();
	}
	
	@Override
	public void update(T entity) {

		FactoryUtilOld factory = new FactoryUtilOld();
		EntityManager manager = factory.getFactory().createEntityManager();

		manager.getTransaction().begin();
		manager.merge(entity);
		manager.getTransaction().commit();
		manager.close();
	}

	@Override
	public void remove(T entity) {
		getEntityManager().getTransaction().begin();
		getEntityManager().remove(entity);
		getEntityManager().getTransaction().commit();

	}

	@Override
	public T getById(Class<T> classe, ID pk) {

		try {
			return getEntityManager().find(classe, pk);
		} catch (NoResultException e) {
			return null;
		}

	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> getAll(Class<T> classe) {

		return getEntityManager().createQuery(
				"select o from " + classe.getSimpleName() + " o")
				.getResultList();
	}

	@Override
	public EntityManager getEntityManager() {

		FactoryUtilOld factory = new FactoryUtilOld();
		return factory.getFactory().createEntityManager();
	}

}
